package com.jianan.mis.app.basedata;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Material;
import com.jianan.mis.service.CountryService;
import com.jianan.mis.service.MaterialService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

@SuppressWarnings("unchecked")
public class CountryView extends ViewPart {

	class CountryListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			Country country = (Country) element;
			return country.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	class CountryContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	class MaterialListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			Material material = (Material) element;
			return material.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	class MaterialContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((Set) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	class MaterialSorter extends ViewerSorter {
		public int compare(Viewer viewer, Object e1, Object e2) {
			Material material1 = (Material) e1;
			Material material2 = (Material) e2;
			return material1.getName().compareTo(material2.getName());
		}
	}
	private ListViewer allListViewer;
	private ListViewer selectedListViewer;
	private org.eclipse.swt.widgets.List allList;
	private org.eclipse.swt.widgets.List selectedList;
	private StyledText txtRemark;
	private Text txtBasePrice;
	private Text txtMaterialPeriod;
	private Text txtName;
	private ComboViewer countryComboViewer;
	private Combo combo;
	public static final String ID = "com.jianan.mis.app.basedata.CountryView"; //$NON-NLS-1$
	
	private CountryService countryService;
	
	private MaterialService materialService;
	
	private Country currentCountry;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		
		if(!initializeServices()) {
			MessageDialog.openError(getViewSite().getShell(),
					IMessageKeys.OPEN_VIEW_FAIL, IMessageKeys.SERVICE_UNAVAILABLE);
			return;
		}
		
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 4;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label.setText("选择国家:");

		countryComboViewer = new ComboViewer(container, SWT.READ_ONLY);
		countryComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(final SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				currentCountry = (Country) selection.getFirstElement();
				txtName.setText(currentCountry.getName());
				txtMaterialPeriod.setText(currentCountry.getMaterialPeriod() != null ? currentCountry.getMaterialPeriod().toString() : "");
				txtBasePrice.setText(currentCountry.getBasePrice() != null ? currentCountry.getBasePrice().toString() : "");
				txtRemark.setText(currentCountry.getRemark() != null ? currentCountry.getRemark() : "");
				selectedListViewer.setInput(currentCountry.getMaterials());
			}
		});
		countryComboViewer.setContentProvider(new CountryContentProvider());
		countryComboViewer.setLabelProvider(new CountryListLabelProvider());
		combo = countryComboViewer.getCombo();
		final GridData gd_combo = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1);
		gd_combo.widthHint = 60;
		combo.setLayoutData(gd_combo);
		countryComboViewer.setInput(countryService.getAll());

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_1.setText("国家名称:");

		txtName = new Text(container, SWT.BORDER);
		final GridData gd_txtName = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1);
		gd_txtName.widthHint = 85;
		txtName.setLayoutData(gd_txtName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("作件最长周期:");

		txtMaterialPeriod = new Text(container, SWT.BORDER);
		final GridData gd_txtMaterialPeriod = new GridData(89, SWT.DEFAULT);
		txtMaterialPeriod.setLayoutData(gd_txtMaterialPeriod);

		final Label label_6 = new Label(container, SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		label_6.setText("(单位为天)");

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("收费基准价:");

		txtBasePrice = new Text(container, SWT.BORDER);
		final GridData gd_txtBasePrice = new GridData(90, SWT.DEFAULT);
		txtBasePrice.setLayoutData(gd_txtBasePrice);

		final Label label_7 = new Label(container, SWT.NONE);
		label_7.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		label_7.setText("(单位为元)");

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
		label_4.setText("备注:");

		txtRemark = new StyledText(container, SWT.MULTI | SWT.BORDER);
		txtRemark.setWordWrap(true);
		final GridData gd_txtRemark = new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1);
		gd_txtRemark.widthHint = 133;
		gd_txtRemark.heightHint = 59;
		txtRemark.setLayoutData(gd_txtRemark);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
		label_5.setText("            选择材料清单:");

		allListViewer = new ListViewer(container, SWT.V_SCROLL | SWT.MULTI | SWT.H_SCROLL | SWT.BORDER);
		allListViewer.setSorter(new MaterialSorter());
		allListViewer.setLabelProvider(new MaterialListLabelProvider());
		allListViewer.setContentProvider(new MaterialContentProvider());
		allList = allListViewer.getList();
		final GridData gd_list = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 3);
		gd_list.widthHint = 120;
		gd_list.heightHint = 140;
		allList.setLayoutData(gd_list);
		Set<Material> set = new HashSet<Material>(materialService.getAll());
		allListViewer.setInput(set);

		new Label(container, SWT.NONE);

		selectedListViewer = new ListViewer(container, SWT.V_SCROLL | SWT.MULTI | SWT.H_SCROLL | SWT.BORDER);
		selectedListViewer.setSorter(new MaterialSorter());
		selectedListViewer.setLabelProvider(new MaterialListLabelProvider());
		selectedListViewer.setContentProvider(new MaterialContentProvider());
		selectedList = selectedListViewer.getList();
		final GridData gd_list_1 = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 3);
		gd_list_1.widthHint = 120;
		gd_list_1.heightHint = 140;
		selectedList.setLayoutData(gd_list_1);
		new Label(container, SWT.NONE);
		
		final Button btnAdd = new Button(container, SWT.NONE);
		btnAdd.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				// 取得选择要添加的material
				IStructuredSelection selections = (IStructuredSelection) allListViewer.getSelection();
				Iterator iterator = selections.iterator();
				Set<Material> selectedMaterials;
				if (selectedListViewer.getInput() != null)
					selectedMaterials = (Set<Material>) selectedListViewer.getInput();
				else
					selectedMaterials = new HashSet<Material>();
				while(iterator.hasNext()) {
					Material material = (Material) iterator.next();
					selectedMaterials.add(material);
				}
				selectedListViewer.setInput(selectedMaterials);
			}
		});
		final GridData gd_btnAdd = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		gd_btnAdd.widthHint = 45;
		btnAdd.setLayoutData(gd_btnAdd);
		btnAdd.setText("添加");
		new Label(container, SWT.NONE);
		
		final Button btnDel = new Button(container, SWT.NONE);
		btnDel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				// 取得选择要移除的material
				IStructuredSelection selections = (IStructuredSelection) selectedListViewer.getSelection();
				Iterator iterator = selections.iterator();
				Set<Material> selectedMaterials = (Set<Material>) selectedListViewer.getInput();
				while(iterator.hasNext()) {
					Material material = (Material) iterator.next();
					selectedMaterials.remove(material);
				}
				selectedListViewer.setInput(selectedMaterials);
			}
		});
		final GridData gd_btnDel = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		gd_btnDel.widthHint = 45;
		btnDel.setLayoutData(gd_btnDel);
		btnDel.setText("移除");
		new Label(container, SWT.NONE);

		final Button btnSave = new Button(container, SWT.NONE);
		btnSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (checkInfo()) {
					Country country = new Country();
					fillCountryFields(country);
					try {
						countryService.save(country);
						reset();
						MessageDialog.openInformation(e.display
								.getActiveShell(), IMessageKeys.SUCCESS,
								"新增国家信息成功!");
					} catch (Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnSave = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnSave.setLayoutData(gd_btnSave);
		btnSave.setText("新增国家");

		final Button btnUpdate = new Button(container, SWT.NONE);
		btnUpdate.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentCountry == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个国家!");
					return;
				}
				if (checkInfo()) {
					fillCountryFields(currentCountry);
					try {
						countryService.update(currentCountry);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "更新国家信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnUpdate = new GridData();
		btnUpdate.setLayoutData(gd_btnUpdate);
		btnUpdate.setText("更新国家");
		final Button btnRemove = new Button(container, SWT.NONE);
		btnRemove.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentCountry == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个国家!");
					return;
				}
				if(MessageDialog.openConfirm(e.display.getActiveShell(), 
						IMessageKeys.CONFIRM, "确认删除该国家吗?")) {
					try {
						countryService.remove(currentCountry);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "删除国家信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
					}
				}
			}
		});
		final GridData gd_btnRemove = new GridData();
		btnRemove.setLayoutData(gd_btnRemove);
		btnRemove.setText("删除国家");
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	private boolean initializeServices() {
		materialService = (MaterialService) SpringBeanFactory.getBean("materialService");
		if(materialService == null) {
			return false;
		}
		countryService = (CountryService) SpringBeanFactory.getBean("countryService");
		if(countryService == null) {
			return false;
		}
		return true;
	}
	
	private void reset() {
		txtName.setText("");
		txtMaterialPeriod.setText("");
		txtBasePrice.setText("");
		txtRemark.setText("");
		allListViewer.setSelection(null);
		selectedListViewer.setInput(null);
		countryComboViewer.setInput(countryService.getAll());
		currentCountry = null;
	}
	
	private void fillCountryFields(Country country) {
		country.setName(txtName.getText());
		if(StringUtils.isNotEmpty(txtMaterialPeriod.getText())) {
			BigDecimal materialPeriod = new BigDecimal(txtMaterialPeriod.getText());
			country.setMaterialPeriod(materialPeriod);
		} else {
			country.setMaterialPeriod(null);
		}
		if(StringUtils.isNotEmpty(txtBasePrice.getText())) {
			BigDecimal basePrice = new BigDecimal(txtBasePrice.getText());
			country.setBasePrice(basePrice);
		} else {
			country.setBasePrice(null);
		}
		country.setRemark(txtRemark.getText());
		country.setMaterials((Set<Material>) selectedListViewer.getInput());
	}
	
	private boolean checkInfo() {
		if(StringUtils.isEmpty(txtName.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入国家名称!");
			return false;
		}
		if(StringUtils.isNotEmpty(txtMaterialPeriod.getText())) {
			try {
				new BigDecimal(txtMaterialPeriod.getText());
			} catch(Exception ex) {
				MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
						IMessageKeys.INFORMATION, "作件最长周期输入不正确，请重新输入!");
				return false;
			}
		}
		if(StringUtils.isNotEmpty(txtBasePrice.getText())) {
			try {
				new BigDecimal(txtBasePrice.getText());
			} catch(Exception ex) {
				MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
						IMessageKeys.INFORMATION, "收费基准价输入不正确，请重新输入!");
				return false;
			}
		}
		return true;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
